<?php

namespace app\logic\admin;

class L_article
{
    /**
     * 删除反斜线
     * @param string $paramObj
     */
    public function removeBackslashes($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'table' => '',
                'column' => 'require',
                'type' => 'require',
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            if($dataObj->request->type=="all_article"){
                $paramsObj=paramsObj();
                $paramsObj->params=array(
                    "module"=>"article",
                    "field"=>"id",
                );
                $checkResult=app("S_Admin_module")->allData($paramsObj);
                if($checkResult["error_no"]=="0"){
                    $modules=$checkResult["result"];
                    if($modules){
                        foreach($modules as $module){
                            $pre=app("cmsTable")->getPre();
                            $sql="UPDATE {$pre}article_{$module['id']} SET {$dataObj->request->column} = REPLACE(`{$dataObj->request->column}`,'\\\\','')";
                            Db()->execute($sql);
                        }
                    }
                }
            }else if($dataObj->request->type=="all_article_data"){
                $paramsObj=paramsObj();
                $paramsObj->params=array(
                    "module"=>"article",
                    "field"=>"id",
                );
                $checkResult=app("S_Admin_module")->allData($paramsObj);
                if($checkResult["error_no"]=="0"){
                    $modules=$checkResult["result"];
                    if($modules){
                        foreach($modules as $module){
                            $pre=app("cmsTable")->getPre();
                            $sql="UPDATE {$pre}article_data_{$module['id']} SET {$dataObj->request->column} = REPLACE(`{$dataObj->request->column}`,'\\\\','')";
                            Db()->execute($sql);
                        }
                    }
                }
            }else{
                if($dataObj->request->table){
                    $pre=app("cmsTable")->getPre();
                    $sql="UPDATE {$pre}{$dataObj->request->table} SET {$dataObj->request->column} = REPLACE(`{$dataObj->request->column}`,'\\\\','')";
                    $ok=Db()->execute($sql);
                    if(!$ok){
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
                    }
                }else{
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
                }
            }
        }
        return $final_arr;
    }

    /**
     * 更新链接地址
     */
    public function updateLinkurl($paramObj=""){
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'moduleId' => 'require',
                'page' => '',
                'pageSize' => '',
                'recursion' => '',
            );
            $dataDefault = array();
            $dataDefault["page"] = "1";
            $dataDefault["pageSize"] = "100";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if($final_arr["error_no"]==0){
            //查询数据
            $paramsObj=paramsObj();
            $paramsObj->params=array(
                "moduleId"=>$dataObj->request->moduleId,
                'page' => $dataObj->request->page,
                'pageSize' => $dataObj->request->pageSize,
                "field"=>"id,moduleId,addTime,categoryId",
            );
            $checkResult=app("S_Admin_article")->getAllData($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $result = $checkResult["result"];
                if($result){
                    $data=array();
                    foreach($result as $val){
                        $data["id"][]=$val["id"];
                        $data["data"][$val["id"]]=itemurl($val);
                    }
                    $case="";
                    foreach($data["id"] as $id){
                        if(isset($data["data"][$id])){
                            $case.="WHEN {$id} THEN '{$data["data"][$id]}' ";
                        }
                    }
                    $tableName=app("cmsTable")::article($dataObj->request->moduleId);
                    $sql="update `{$tableName}` set linkUrl = CASE id {$case} END where id IN(".implode(",",$data["id"]).")";
                    Db()->execute($sql);

                    if(count($result)==$dataObj->request->pageSize &&  $dataObj->request->recursion){
                        $paramsObj=paramsObj();
                        $paramsObj->params=array(
                            'moduleId' => $dataObj->request->moduleId,
                            'page' =>intval($dataObj->request->page) + 1,
                            'pageSize' =>$dataObj->request->pageSize,
                            'recursion' =>$dataObj->request->recursion,
                        );
                        $checkResult=$this->updateLinkurl($paramsObj);
                        if ($checkResult["error_no"] == 0) {

                        }else{
                            $final_arr = logCallErrorMsg($final_arr, $checkResult);
                        }
                    }
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        return $final_arr;
    }

    /**
     * 创建资源
     * @param string $paramObj
     */
    public function store($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'number',
                'categoryId' => 'require|number',
                'moduleId' => 'require|integer',
                'webTitle' => '',
                'webKeyWords' => '',
                'title' => 'require',
                'thumb' => '',
                'description' => '',
                'status' => '',
                'author' => '',
                'content' => '',
                'addTime' => '',
                'hits' => '',
                'level' => '',
                'post_fields' => '',
                'urlReplace' => '',
                'isAdmin' => 'require|integer',
                'userId' => 'require|integer',
                'downloadImages' => '',         //下载远程图片
                'clearLink' => '',         //清除链接a标签
                'extractContentToDescription' => '',         //截取指定字符到简介
                'setNumberImgToThumbnail' => '',         //指定第x图片当缩略图
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->noFilter=array("thumb");
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //内容处理
        if ($final_arr["error_no"] == 0) {
            if ($dataObj->request->downloadImages) { //下载远程图片
                $dataObj->request->content = $this->downloadImages($dataObj->request->content);
            }
            if ($dataObj->request->clearLink) { //清除连接 a标签
                $dataObj->request->content = $this->clearLink($dataObj->request->content);
            }
            if($dataObj->request->urlReplace){
                //url替换
//                $dataObj->request->content=$this->urlReplace($dataObj->request->content,$dataObj->request->moduleId);
            }
            if ($dataObj->request->extractContentToDescription) { //截取指定字符文章到简介
                if(!$dataObj->request->description){
                    $dataObj->request->description = $this->extractContentToDescription($dataObj->request->content, $dataObj->request->extractContentToDescription);
                }
            }
            if ($dataObj->request->setNumberImgToThumbnail && !$dataObj->request->thumb) { //指定第x张图为缩略图
                $dataObj->request->thumb = $this->setNumberImgToThumbnail($dataObj->request->content, $dataObj->request->setNumberImgToThumbnail);
            }
            $text_editor=getSelecdTextEditor();
            if(in_array($text_editor,array("ueditor"))){
                $dataObj->request->content = str_replace("&nbsp;"," ",$dataObj->request->content);
            }
            $dataObj->request->content = dhtmlspecialchars($dataObj->request->content);
        }
        if ($final_arr["error_no"] == 0) {
            Db()->startTrans();
            $dataObj->data->use_trans = true;
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
                "moduleId" => $dataObj->request->moduleId,
                'webTitle' => dhtmlspecialchars($dataObj->request->webTitle),
                'webKeyWords' => dhtmlspecialchars($dataObj->request->webKeyWords),
                'title' => dhtmlspecialchars($dataObj->request->title),
                'thumb' => $dataObj->request->thumb,
                'description' => dhtmlspecialchars($dataObj->request->description),
                'status' => $dataObj->request->status,
                'author' => dhtmlspecialchars($dataObj->request->author),
                'isAdmin' => $dataObj->request->isAdmin,
                'userId' => $dataObj->request->userId,
                'addTime' => $dataObj->request->addTime,
                'level' => $dataObj->request->level,
                'categoryId' => $dataObj->request->categoryId,
                'post_fields' => $dataObj->request->post_fields,
                'hits' => $dataObj->request->hits,
            );
            $checkResult = app("S_Admin_article")->store($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $result = $checkResult["result"];
                if (isset($dataObj->request->content)) {
                    $paramsObj = paramsObj();
                    $paramsObj->params = array(
                        "articleId" => $result["id"],
                        "moduleId" => $dataObj->request->moduleId,
                        "articleContent" => $dataObj->request->content,
                    );
                    $checkResult = app("S_Admin_articleData")->record($paramsObj);
                    if ($checkResult["error_no"] == 0) {
                        $final_arr["result"] = $result;
                    } else {
                        $final_arr = logCallErrorMsg($final_arr, $checkResult);
                    }
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($dataObj->data->use_trans) {
            if ($final_arr["error_no"] == 0) {
                Db()->commitTrans();
            } else {
                Db()->rollbackTrans();
            }
        }
        return $final_arr;
    }

    /**
     * 更新资源
     * @param string $paramObj
     */
    public function update($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'categoryId' => 'require|number',
                'moduleId' => 'require|integer|gt:0',
                'id' => 'require|integer|gt:0',
                'webTitle' => '',
                'webKeyWords' => '',
                'title' => 'require',
                'thumb' => '',
                'description' => '',
                'status' => '',
                'author' => '',
                'hits' => '',
                'level' => '',
                'content' => '',
                'addTime' => '',
                'urlReplace' => '',
                'post_fields' => '',
                'downloadImages' => '',         //下载远程图片
                'clearLink' => '',         //清除链接a标签
                'extractContentToDescription' => '',         //截取指定字符到简介
                'setNumberImgToThumbnail' => '',         //指定第x图片当缩略图
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->noFilter=array("thumb","content");
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //内容处理
        if ($final_arr["error_no"] == 0) {
            if ($dataObj->request->downloadImages) { //下载远程图片
                $dataObj->request->content = $this->downloadImages($dataObj->request->content);
            }
            if ($dataObj->request->clearLink) { //清除连接 a标签
                $dataObj->request->content = $this->clearLink($dataObj->request->content);
            }
            if($dataObj->request->urlReplace){
                //url替换
//                $dataObj->request->content=$this->urlReplace($dataObj->request->content,$dataObj->request->moduleId);
            }
            if ($dataObj->request->extractContentToDescription) { //截取指定字符文章到简介
                if(!$dataObj->request->description){
                    $dataObj->request->description = $this->extractContentToDescription($dataObj->request->content, $dataObj->request->extractContentToDescription);
                }
            }
            if ($dataObj->request->setNumberImgToThumbnail  && !$dataObj->request->thumb) { //指定第x张图为缩略图
                $dataObj->request->thumb = $this->setNumberImgToThumbnail($dataObj->request->content, $dataObj->request->setNumberImgToThumbnail);
            }
            $text_editor=getSelecdTextEditor();
            if(in_array($text_editor,array("ueditor"))){
                $dataObj->request->content = str_replace("&nbsp;"," ",$dataObj->request->content);
            }
            $dataObj->request->content = dhtmlspecialchars($dataObj->request->content);
        }
        if ($final_arr["error_no"] == 0) {
            Db()->startTrans();
            $dataObj->data->use_trans = true;
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
                "moduleId" => $dataObj->request->moduleId,
                'webTitle' => dhtmlspecialchars($dataObj->request->webTitle),
                'webKeyWords' => dhtmlspecialchars($dataObj->request->webKeyWords),
                'title' => dhtmlspecialchars($dataObj->request->title),
                'thumb' => $dataObj->request->thumb,
                'description' => dhtmlspecialchars($dataObj->request->description),
                'status' => $dataObj->request->status,
                'author' => dhtmlspecialchars($dataObj->request->author),
                'level' => $dataObj->request->level,
                'addTime' => $dataObj->request->addTime,
                'categoryId' => $dataObj->request->categoryId,
                'post_fields' => $dataObj->request->post_fields,
                'hits' => $dataObj->request->hits,
            );
            $checkResult = app("S_Admin_article")->update($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $result = $checkResult["result"];
                if (isset($dataObj->request->content)) {
                    $paramsObj = paramsObj();
                    $paramsObj->params = array(
                        "articleId" => $dataObj->request->id,
                        "moduleId" => $dataObj->request->moduleId,
                        "articleContent" => $dataObj->request->content,
                    );
                    $checkResult = app("S_Admin_articleData")->record($paramsObj);
                    if ($checkResult["error_no"] == 0) {
                        $final_arr["result"] = $result;
                    } else {
                        $final_arr = logCallErrorMsg($final_arr, $checkResult);
                    }
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($dataObj->data->use_trans) {
            if ($final_arr["error_no"] == 0) {
                Db()->commitTrans();
            } else {
                Db()->rollbackTrans();
            }
        }
        return $final_arr;
    }

    /**
     * url替换
     * @param $content
     * @return mixed
     */
    public function urlReplace($content,$moduleId){
        //获取内链替换数据
        $url_replace_by_word=setting("url_replace_by_word",$moduleId);
        $url_replace_by_word_limit=setting("url_replace_by_word_limit",$moduleId);
        if($url_replace_by_word){
            $words=explode("\n",$url_replace_by_word);
            if($words){
                $search=array();
                $replace=array();
                $placeholder=array();
                foreach($words  as $val){
                    if($val){
                        list($key,$val,$limit)=array_pad(explode("@",trim($val)),3,"");
                        if($key && $val){
                            $impulseSender=impulseSender();
                            $tmp=array();
                            $tmp["key"]=trim($key);
                            $tmp["val"]=trim($val);
                            $tmp["placeholder"]=$impulseSender;
                            $tmp["limit"]=trim($limit)?intval(trim($limit)):($url_replace_by_word_limit?intval(trim($url_replace_by_word_limit)):null);
                            $tmp["val"]='<a href="'.$tmp["val"].'" target="_blank" >'.$tmp["key"].'</a>';
                            $replace[$key]=$tmp;
                            $search[]=$tmp["key"];
                            $placeholder[$impulseSender]=$tmp["val"];
                        }
                    }
                }
                if($search){
                    // 按照搜索数组的长度降序排序
                    usort($search, 'sortByLength');
                    //匹配a链接，先用占位符占位。
                    $a_reg="/<a[^>]*>([^<]*)<\/a>/i";
                    $ok=preg_match_all($a_reg,$content,$matches);
                    $priority=array();
                    if($ok && $matches){
                        foreach($matches[0] as $val){
                            if($val){
                                $impulseSender=impulseSender();
                                $priority[$impulseSender]=$val;
                                $content=str_replace($val,$impulseSender,$content);
                            }
                        }
                        foreach($matches[1] as $val){
                            if(isset($replace[$val]["limit"])){
                                $limit=$replace[$val]["limit"];
                                if(isset($limit)){
                                    $replace[$val]["limit"]=$limit-1;
                                }
                            }
                        }
                    }
                    // 使用 str_replace 进行替换
                    foreach ($search as $value) {
                        $limit=$replace[$value]["limit"];
                        $regVal="/".preg_quote($value,"/")."/";
                        if(isset($limit)){
                            if($limit >0){
                                $content = preg_replace($regVal, $replace[$value]["placeholder"], $content,$limit);
                            }
                        }else{
                            $content = preg_replace($regVal, $replace[$value]["placeholder"], $content);
                        }
                    }
                    //替换需替换数据
                    $content=str_replace(array_keys($placeholder),array_values($placeholder),$content);
                    //反替换回去
                    if($priority){
                        $content=str_replace(array_keys($priority),array_values($priority),$content);
                    }
                }
            }
        }
        return $content;
    }

    /**
     * 删除资源
     * @param string $paramObj
     */
    public function delete($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
                'moduleId' => 'require|integer|gt:0',
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            Db()->startTrans();
            $dataObj->data->use_trans = true;
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
                "moduleId" => $dataObj->request->moduleId,
            );
            $checkResult = app("S_Admin_article")->delete($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $result = $checkResult["result"];
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => $dataObj->request->id,
                    "moduleId" => $dataObj->request->moduleId,
                );
                $checkResult = app("S_Admin_articleData")->delete($paramsObj);
                if ($checkResult["error_no"] == 0) {
                    $final_arr["result"] = $result;
                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($dataObj->data->use_trans) {
            if ($final_arr["error_no"] == 0) {
                Db()->commitTrans();
            } else {
                Db()->rollbackTrans();
            }
        }
        return $final_arr;
    }

    /**
     * 获取资源
     * @param string $paramObj
     */
    public function info($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'moduleId' => 'require|integer|gt:0',
                'id' => 'require|integer|gt:0',
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
                "moduleId" => $dataObj->request->moduleId,
            );
            $checkResult = app("S_Admin_article")->info($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $rowData = $checkResult["result"];
                if ($rowData) {
                    $dataObj->result = $rowData;
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            if ($dataObj->result) {
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => $dataObj->result["id"],
                    "moduleId" => $dataObj->request->moduleId,
                );
                $checkResult = app("S_Admin_articleData")->info($paramsObj);
                if ($checkResult["error_no"] == 0) {
                    $dataObj->result["articleContent"] = $checkResult["result"] ? $checkResult["result"]["articleContent"] : "";
                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            }
        }
        if ($final_arr["error_no"] == 0) {
            $final_arr["result"] = $dataObj->result;
        }
        return $final_arr;
    }


    /**
     * 批量修改状态
     * @param string $paramObj
     */
    public function setStatus($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
                'moduleId' => 'require|integer|gt:0',
                'status' => 'require|between:1,4',
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
                "moduleId" => $dataObj->request->moduleId,
                "status" => $dataObj->request->status,
            );
            $checkResult = app("S_Admin_article")->update($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $final_arr["result"] = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        return $final_arr;
    }

    /**
     * 批量修改回收站
     * @param string $paramObj
     */
    public function setRecycle($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
                'moduleId' => 'require|integer|gt:0',
                'recycle' => 'require|between:1,2',
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
                "moduleId" => $dataObj->request->moduleId,
                "recycle" => $dataObj->request->recycle,
            );
            $checkResult = app("S_Admin_article")->update($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $final_arr["result"] = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        return $final_arr;
    }


    //下载文章远程图片
    private function downloadImages($content = "")
    {

        // 要匹配的文本
        $text = $content;
        // 正则表达式 匹配图片标签, stc链接
        $pattern = <<<aaa
/<img .*?src="(http.*?)"/
aaa;

        // 获取匹配数量
        preg_match_all($pattern, $text, $matches);
        $matchCount = count($matches[0]);
        // for循环内获取匹配文本和第一个子匹配文本
        for ($i = 0; $i < $matchCount; $i++) {
            $matchText = $matches[0][$i];
            $imgUrl = $matches[1][$i];
            //打开输出缓冲区并获取远程图片
            $img =  $this->http_get($imgUrl);
            $imgType = $this->getImgType($img); //判断是否为图片,和获取图片真实后缀
            if (!$imgType){ //可能会404
                //不是图片或下载失败了 跳过
                continue;
            }
            $imgMd5 = md5($img);
            $date=app("yifangTime")::getDateTime("Ym/d");
            $newImgPath = "/upload/{$date}/$imgMd5.$imgType";
            if (!is_dir(YIFANG_ROOT . "/public/upload/{$date}")) {
                mkdir(YIFANG_ROOT . "/public/upload/{$date}", 0777, true);
            }
            if (!$imgType || !file_put_contents(YIFANG_ROOT . "/public" . $newImgPath, $img)) {
                //不是图片,或写入本地失败了就不替换跳过
                continue;
            }
            //替换文章内容
            //https://pics5.baidu.com/feed/4a36acaf2edda3cc2b38500d26ca240c203f92eb.jpeg@f_auto?token=a35148363bd7dbfc89be6e4dc1728ac8
            $newImgPath = str_replace($imgUrl, $newImgPath, $matchText);
            $content = str_replace($matchText, $newImgPath, $content);
        }
        return $content;
    }

    /**
     * http请求
     * @param $url
     * @return mixed
     */
    public function http_get($url)
    {
        $headers = array(
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Language: zh-CN,zh;q=0.9',
            'Cache-Control: no-cache',
            'Connection: keep-alive',
            'DNT: 1',
            'Host: so.toutiao.com',
            'Pragma: no-cache',
            'Referer: ' . $url,
            'Sec-Fetch-Dest: document',
            'Sec-Fetch-Mode: navigate',
            'Sec-Fetch-Site: same-origin',
            'Sec-Fetch-User: ?1',
            'Upgrade-Insecure-Requests: 1',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36',
            'sec-ch-ua: "Not.A/Brand";v="8", "Chromium";v="114"',
            'sec-ch-ua-mobile: ?0',
            'sec-ch-ua-platform: "Windows"'
        );
        $method="get";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); //是否抓取跳转后的页面
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    //判断获取图片字节数组格式
    private function getImgType($img)
    {
        // 判断下载回来的是否为图片
        $imageInfo = getimagesizefromstring($img);

        if ($imageInfo !== false) {
            // 获取图像类型
            $imageType = $imageInfo[2];
            // 判断图像类型是否为有效的图像类型
            if ($imageType) {
                $imgList = [1 => "GIF",
                    2 => "JPG",
                    3 => "PNG",
                    4 => "SWF",
                    5 => "PSD",
                    6 => "BMP",
                    7 => "TIFF(intel byte order)",
                    8 => "TIFF(motorola byte order)",
                    9 => "JPC",
                    10 => "JP2",
                    11 => "JPX",
                    12 => "JB2",
                    13 => "SWC",
                    14 => "IFF",
                    15 => 'WBMP',
                    16 => 'XBM'
                ];
                if ($imageType < 1 || $imageType > 16) {
                   return "JPG";
                    return false;
                }

                return $imgList[$imageType];
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    //清除连接  文章内a标签清除
    private function clearLink($content = "")
    {

        // 要匹配的文本
        $text = $content;
        // 正则表达式 匹配a标签, 文本内容
        $pattern = <<<aaa
/<a.*?">(.*?)<\Wa>/
aaa;

        // 获取匹配数量
        preg_match_all($pattern, $text, $matches);
        $matchCount = count($matches[0]);
        // for循环内获取匹配文本和第一个子匹配文本
        for ($i = 0; $i < $matchCount; $i++) {
            $matchText = $matches[0][$i];
            $text = $matches[1][$i];
            //替换a标签为文章内容
            $content = str_replace($matchText, $text, $content);
        }
        return $content;

    }

    //截取指定文章字符 过滤标签
    private function extractContentToDescription($content = "", $number = 0/*截取长度*/)
    {
        $text = strip_tags($content);
        $text = preg_replace("/\s+/", "",$text);
        return mb_substr($text, 0, $number, 'utf-8');
    }

    //指定第x张贴为缩略图
    private function setNumberImgToThumbnail($content = "", $number = 0/*第几长图*/, $pid = null)
    {

        // 要匹配的文本
        $text = $content;
        // 正则表达式 匹配图片标签, stc链接
        $pattern = <<<aaa
/<img .*?src="(.*?)"/
aaa;

        // 获取匹配数量
        preg_match_all($pattern, $text, $matches);
        $matchCount = count($matches[0]);
        if ($number > $matchCount || $number <= 0) {
            return "";
        }
        $imgUrl = $matches[1][$number-1]; //1为子匹配数组
        //http开头验证 如果是本地图片转换图片为指定缩略图宽高否则直接返回
        if (strpos($imgUrl, "http") === 0) {
            return $imgUrl;
        }
        // 目标宽度和高度
        $targetWidth = setting("thumbWidth", $pid)??0;
        $targetHeight = setting("thumbHeight", $pid)??0;
        if (!$targetWidth || !$targetHeight) { //没有值不缩放
            return $imgUrl;
        }

        $newImg = img_resizeImage(YIFANG_ROOT . "/public" . $imgUrl, $targetWidth, $targetHeight);
        if (!$newImg) { //失败就返回原图片
            return $imgUrl;
        }
        $imgMd5 = md5($newImg["img"]);

        $newImgPath = config("template.replace.__INDEX_STATIC__", "") . "/img/" . $imgMd5 . "." . $newImg['extension'];

        if (!is_dir(YIFANG_ROOT . "/public" . config("template.replace.__INDEX_STATIC__", "") . "/img")) {
            mkdir(YIFANG_ROOT . "/public" . config("template.replace.__INDEX_STATIC__", "") . "/img", 0777, true);
        }
        if (!file_put_contents(YIFANG_ROOT . "/public" . $newImgPath, $newImg["img"])) {
            //不是图片,或写入本地失败了就不替换跳过
            return $imgUrl;
        }
        //成功返回新图片路径
        return $newImgPath;

    }

    //获取别名转别名数组
    public function getlevelAlias($levelAlias = "")
    {
        $array = array();
        $aliasList = explode("|", $levelAlias); // 将内容按行分割到数组中
        for ($i = 1; $i < 10; $i++) {
            $array[$i] = array_key_exists($i-1, $aliasList) ? $i . "级 " . $aliasList[$i-1] : $i . "级";
        }
        return $array;
    }

    //批量保存相关设置
    public function settingRecordBatch($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'setting' => '',
                'config' => '',
                'pid' => 'require',
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "pid" => $dataObj->request->pid,
                "setting" => $dataObj->request->setting,
                "config" => $dataObj->request->config,
            );
            $checkResult = app("L_Admin_setting")->recordBatch($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $final_arr["result"] = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        return $final_arr;
    }

}